<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/9
 * Time: 13:44
 */
class DbHelper{
    private $dbHandler;
    public function __construct(){
        $this->dbHandler = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    }

    public function insert($table, $data){
        $bulk = new MongoDB\Driver\BulkWrite();
        $bulk->insert($data);
        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
        $result = $this->dbHandler->executeBulkWrite($table, $bulk, $writeConcern);
        $res = $result->getInsertedCount();
        if ($res <= 0){
            throw new Error('数据库插入异常');
        }
        return $res;
    }

    public function update($table, $where, $data, $upsert=false){
        $bulk = new MongoDB\Driver\BulkWrite();
        $bulk->update($where, ['$set' => $data], ['multi' => false, 'upsert' => $upsert]);
        $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
        $result = $this->dbHandler->executeBulkWrite($table, $bulk, $writeConcern);
        $res = $result->getInsertedCount();
        if ($res <= 0){
            throw new Error('数据库修改异常');
        }
        return $res;
    }

    public function select($table, $filter = [], $options = []){
        $query = new MongoDB\Driver\Query($filter, $options);
        $readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
        $cursor = $this->dbHandler->executeQuery($table, $query, $readPreference)->toArray();
        return $cursor;
    }
}